package com.itzhigui.controller.api;

import com.itzhigui.entity.User;
import com.itzhigui.service.CartService;
import com.itzhigui.utils.ConstantUtil;
import com.itzhigui.utils.ResponseEnum;
import com.itzhigui.utils.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @author java1412
 * @since 2023-11-14 17:24:33
 */
@RestController
@Slf4j
@RequestMapping(value = "/api/cart")
@Api(value = "前台购物车", tags = "ApiCartController")
public class ApiCartController {

    @Resource
    private CartService cartService;

    @ApiOperation(value = "获取购物车数量", notes = "前台获取购物车数量")
    @GetMapping(value = "/findCartCount")
    public ResponseUtil findCartCount(
            HttpSession session
    ) {
        User loginUser = (User) session.getAttribute(ConstantUtil.LOGIN_USER_KEY);
        ResponseUtil r = null;
        if (loginUser != null) {
            Integer userId = loginUser.getId();
            r = cartService.findCountByUserId(userId);
        } else {
            r = ResponseUtil.get(ResponseEnum.CART_FIND_COUNT_FAILURE, null);
        }
        return r;
    }

    // 获取购物车的详细信息
    @ApiOperation(value = "获取购物车信息", notes = "前台获取购物车信息")
    @GetMapping(value = "/findCart")
    public ResponseUtil findCart(
            HttpSession session
    ) {
        User loginUser = (User) session.getAttribute(ConstantUtil.LOGIN_USER_KEY);
        return cartService.findCartByUser(loginUser.getId());
    }

    // 更新购物车的状态,参数id,quantity,checked
    @ApiOperation(value = "更新购物车信息", notes = "前台更新购物车信息")
    @PostMapping(value = "/updateCart")
    public ResponseUtil updateCart(
            @RequestParam("id") Integer id,
            @RequestParam("quantity") Integer quantity,
            @RequestParam("checked") Integer checked
    ) {
        return cartService.updateCart(id, quantity, checked);
    }

    // 根据id删除购物车信息
    @ApiOperation(value = "根据id删除购物车", notes = "根据id删除购物车")
    @GetMapping(value = "/deleteById")
    public ResponseUtil deleteById(
            Integer id
    ) {
        return cartService.deleteCartById(id);
    }

    @ApiOperation(value = "批量删除购物车", notes = "批量删除购物车")
    @GetMapping(value = "/deleteByIds")
    public ResponseUtil deleteByIds(Integer[] ids) {
        return cartService.deleteCartByIds(ids);
    }

    @ApiOperation(value = "清空购物车", notes = "清空购物车")
    @GetMapping(value = "/truncateCart")
    public ResponseUtil truncateCart(
            HttpSession session
    ) {
        User loginUser = (User) session.getAttribute(ConstantUtil.LOGIN_USER_KEY);
        return cartService.truncateCartByUserId(loginUser.getId());
    }
}
